package cn.wgx.modules.sys.services;

import cn.wgx.modules.base.services.BaseService;
import cn.wgx.modules.sys.entity.SysPermission;
import cn.wgx.modules.sys.entity.SysPermissionExample;
import cn.wgx.modules.sys.entity.mapper.SysPermissionMapper;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysPermissionService extends BaseService<SysPermission> {

    public static final String cacheName = "permissionCache";

    @Resource
    private SysPermissionMapper sysPermissionMapper;

    @Cacheable(value = cacheName,  key = "#root.target.getCachePreKey() + \"all_list\"")
    @Transactional(readOnly = true)
    public List<SysPermission> getList() {
        SysPermissionExample example = new SysPermissionExample();
        List<SysPermission> permissions = sysPermissionMapper.selectByExample(example);
        if(logger.isDebugEnabled()){
            logger.debug("--------------------- 获取权限没走缓存 ---------------------------");
        }
        return permissions;
    }

    @Cacheable(value = cacheName,  key = "#root.target.getCachePreKey() + \"all_menu\"")
    @Transactional(readOnly = true)
    public List<SysPermission> getMenu() {
        SysPermissionExample example = new SysPermissionExample();
        example.createCriteria().andMenu_flagEqualTo("Y");
        List<SysPermission> permissions = sysPermissionMapper.selectByExample(example);
        if(logger.isDebugEnabled()){
            logger.debug("--------------------- 获取菜单没走缓存 ---------------------------");
        }
        return permissions;
    }

    @Transactional(readOnly = true)
    public List<SysPermission> getListByIds(List<Integer> ids) {
        if(ids == null || ids.isEmpty()){
            return emptyList;
        }
        List<Integer> uniList = getUniList(ids);
        if(!uniList.isEmpty()){
            SysPermissionExample example = new SysPermissionExample();
            SysPermissionExample.Criteria criteria = example.createCriteria();
            criteria.andPermission_idIn(uniList);
            List<SysPermission> eduCourseAssignmentHis = sysPermissionMapper.selectByExample(example);
            return eduCourseAssignmentHis;
        }
        return null;
    }

//    @Transactional(readOnly = true)
//    @Cacheable(value = cacheName, unless="#result == null || #result.isEmpty()", key = "#root.target.getCachePreKey() + \"byUserId_\" + #user_id ")
//    public List<SysPermission> getPermissionsByUserId(Integer user_id) {
//        List<SysPermission> sysPermissionList = sysPermissionMapper.selectByUserId(user_id);
//        return sysPermissionList;
//    }

    @Transactional(readOnly = true)
    @Cacheable(value = cacheName, unless="#result == null", key = "#root.target.getCachePreKey() + \"byRole_\" + #role_id ")
    public List<SysPermission> getPermissionsByRoleId(Integer role_id) {
        SysPermissionExample example = new SysPermissionExample();
        SysPermissionExample.Criteria criteria = example.createCriteria();
        addCustomSQL(criteria, " t.permission_id in (select permissionId from sys_role_permission where roleId="+role_id+") and 1=", "1");
        List<SysPermission> permissions = sysPermissionMapper.selectByExample(example);
        return permissions;
    }


    @Transactional(readOnly = true)
    @Cacheable(value = cacheName, unless="#result == null", key = "#root.target.getCachePreKey() + \"byDuty_\" + #duty_id ")
    public List<SysPermission> getPermissionsByDutyId(Integer duty_id) {
        SysPermissionExample example = new SysPermissionExample();
        SysPermissionExample.Criteria criteria = example.createCriteria();
        addCustomSQL(criteria, " t.permission_id in (select permission_id from sys_duty_permission where duty_id="+duty_id+") and 1=", "1");
        List<SysPermission> permissions = sysPermissionMapper.selectByExample(example);
        return permissions;
    }

    @Transactional(readOnly = true)
    @Cacheable(value = cacheName, unless="#result == null", key = "#root.target.getCachePreKey() + \"byUser_\" + #user_id ")
    public List<SysPermission> getPermissionsByUserId(Integer user_id) {
        SysPermissionExample example = new SysPermissionExample();
        SysPermissionExample.Criteria criteria = example.createCriteria();
        addCustomSQL(criteria, " t.permission_id in (select permissionId from sys_user_permission where userId="+user_id+") and 1=", "1");
        List<SysPermission> permissions = sysPermissionMapper.selectByExample(example);
        return permissions;
    }

    @Transactional(readOnly = true)
    @CacheEvict(value = cacheName, allEntries=true)
    public void clearListCache() { /*清缓存用*/}


    @Transactional
    @CacheEvict(value = cacheName, allEntries=true)
    public SysPermission insertOne( SysPermission record) {
        sysPermissionMapper.insertSelective(record);
        return record;
    }


    @Transactional
    @CacheEvict(value = cacheName, allEntries=true)
    public int updateOne(SysPermission record) {
        return sysPermissionMapper.updateByPrimaryKeySelective(record);
    }


    @Transactional
    @CacheEvict(value = cacheName, allEntries=true)
    public int deleteOne(Integer id) {
        return sysPermissionMapper.deleteByPrimaryKey(id);
    }


    public void filter(SysPermission record, boolean insert){
        if(insert){

        }else{

        }
        super.filter(record, insert);

    }

    /**
     * 变树
     * @param permissions
     * @return
     */
    public static JSONArray sortPermission(List<SysPermission> permissions){
        JSONArray jsonArray = new JSONArray();
        JSONArray jsonArray_tmp = new JSONArray();
        for(int n=permissions.size(),i=0;i<n; i++){
            SysPermission permission = permissions.get(i);
            if(permission.getParent_key().equals("0")){
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(permission).toString());
                jsonArray.add(jsonObject);
                jsonArray_tmp.add(jsonObject);
                permissions.remove(i);
                i--;
                n = permissions.size();
            }
        }
        addPermission(permissions, jsonArray_tmp);
        return jsonArray;
    }


    private static void addPermission(List<SysPermission> permissions,   JSONArray jsonArray_tmp){
        int len = permissions.size();
        for(int n=len,i=0;i<n; i++){
            SysPermission permission = permissions.get(i);
            for(Object o: jsonArray_tmp){
                JSONObject s = (JSONObject)o;
                if(permission.getParent_key().equals(s.getString("permissionKey"))){
                    JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSON(permission).toString());
                    JSONArray jsonArray1 = s.getJSONArray("children");
                    if(jsonArray1 == null){
                        jsonArray1 = new JSONArray();
                        s.put("children",jsonArray1);
                    }
                    jsonArray1.add(jsonObject);
                    jsonArray_tmp.add(jsonObject);
                    permissions.remove(i);
                    i--;
                    n = permissions.size();
                    break;
                }
            }
        }
        int len_end = permissions.size();
        if(len_end == 0 || len_end ==len){
            //结束
        }else{
            addPermission(permissions,  jsonArray_tmp);
        }
    }
}